package com.dragon.common.modules.file.service.impl;

import com.chris.dev.base.libs.v1.http.params.ResourceParam;
import com.chris.dev.base.libs.v1.http.results.ResourceResult;
import com.dragon.common.base.exceptions.CommonException;
import com.dragon.common.modules.file.common.config.ConditionalOnFileStrategy;
import com.dragon.common.modules.file.common.enums.MediaTypeEnum;
import com.dragon.common.modules.file.domain.dto.SaveFileInfo;
import com.dragon.common.modules.file.service.assistants.FileAssistant;
import com.dragon.common.modules.file.service.assistants.SeaweedFSAssistant;
import com.dragon.common.modules.file.service.def.FileService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author Chris Chan
 * Create On 2025/8/31 下午6:28
 * Use for: seaweedfs文件服务
 * Explain:
 */
@Service
@ConditionalOnFileStrategy("seaweedfs")
public class SeaweedFSServiceImpl implements FileService {
    @Autowired
    private FileAssistant fileAssistant;
    @Autowired
    private SeaweedFSAssistant seaweedFSAssistant;

    @Override
    public ResourceResult uploadWithName(String fileName, MultipartFile file) {
        // 1. 获取文件名
        if (StringUtils.isBlank(fileName)) {
            throw CommonException.of("文件名为空");
        }

        try {
            return seaweedFSAssistant.uploadBytes(fileName, file.getBytes());
        } catch (IOException e) {
            throw CommonException.of("seaweedfs文件上传失败");
        }
    }

    @Override
    public ResourceResult uploadFile(int mode, MultipartFile file) {
        //1. 获取文件名
        String fileName = file.getOriginalFilename();
        //2. 获取并转换媒体类型
        MediaTypeEnum mediaType = FileAssistant.getMediaType(file);
        //3. 构建存储文件信息:存储文件名 存储文件位置 URI
        SaveFileInfo saveFileInfo = fileAssistant.buildSaveFileInfo(mode, mediaType, fileName);
        try {
            return seaweedFSAssistant.uploadBytes(saveFileInfo.getName(), file.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
            throw CommonException.of("seaweedfs文件上传失败");
        }
    }

    @Override
    public ResourceResult uploadBase64(ResourceParam param) {
        //1. 解析参数
        int mode = param.getType();
        String contentBase64 = param.getContentBase64();
        //2. 内容解码
        byte[] contentBytes = fileAssistant.parseBase64(contentBase64);
        //4. 构建存储文件信息:存储文件名 存储文件位置 URI(需要加一个参数指明媒体类型，或者从数据中解析)
        SaveFileInfo saveFileInfo = fileAssistant.buildSaveFileInfo(mode, MediaTypeEnum.FILE, param.getFileName());
        try {
            return seaweedFSAssistant.uploadBytes(saveFileInfo.getName(), contentBytes);
        } catch (Exception e) {
            e.printStackTrace();
            throw CommonException.of("seaweedfs文件上传失败");
        }
    }
}
